package swa2012.telco.provider;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import swa2012.telco.broker.Broker;
import swa2012.telco.broker.BrokerRegistrationStatus;
import swa2012.telco.broker.BrokerSendMessageStatus;
import swa2012.telco.broker.Client;
import swa2012.telco.broker.Message;
import swa2012.telco.broker.Provider;

@WebService(endpointInterface = "swa2012.telco.provider.IProvider")
public class ProviderImpl implements IProvider {

	private static ProviderImpl instance = new ProviderImpl();
	private Broker broker;
	private Provider providerBean = new Provider();

//	private Map<String, Client> clientMap = new HashMap<String, Client>();
//	private List<Client> clientList = new ArrayList<Client>();
	private ClientContainer clientContainer = ClientContainer.getInstance();

	
	private ProviderImpl() {}
	
	public static ProviderImpl getInstance() {
		return instance ;
	}
	

	public BrokerRegistrationStatus connectBroker() {
		
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		factory.setServiceClass(Broker.class);
		factory.setAddress("https://swa.univie.ac.at/TelcoBroker/BrokerService");
		broker = (Broker) factory.create();

		providerBean.setID("13");
		providerBean.setBrokerCallbackEndpoint("http://student.swa.univie.ac.at:8013/telco/BrokerCallback");

		return broker.registerProvider(providerBean);
	}

	public void disconnectBroker() {
		broker.deregisterProvider(providerBean);
		
	}

	public void registerClient(Client client) {
//		clientMap.put(client.getID(), client);
//		clientList.add(client);
		clientContainer.registerClient(client);
		
	}

	public void unregisterClient(Client client) {
		clientContainer.unregisterClient(client);
		
	}

	public BrokerSendMessageStatus sendMessage(Message message) {
		BrokerSendMessageStatus status;
		status = broker.sendMessage(message);
		return status;
	}

	public void fetchMessage() {
		// TODO Auto-generated method stub
		
	}

	public List<Client> getClientList() {
		return broker.listClients();
	}

}
